// API配置文件
export const API_CONFIG = {


    // 测试一个提交(限制git)

    // 后端API基础地址
    BASE_URL: 'http://47.100.202.3:8090',
	//BASE_URL: 'http://localhost:8080',


    // API端点
    ENDPOINTS: {
        // 用户相关
        USER_CHECK: '/api/user/check-user',
        USER_LOGIN: '/api/user/wechat-login',
        USER_INFO: '/api/user/info',
        USER_STATS: '/api/user/stats',
        USER_UPDATE: '/api/user/update',

        // 首页相关
        HOME_DATA: '/api/home/data',

        // 轮播图相关
        BANNER_LIST: '/api/banner/list',
        BANNER_ALL: '/api/banner/all',
        BANNER_DETAIL: '/api/banner',
        // BANNER_ADD: '/api/banner/add',
        BANNER_UPDATE: '/api/banner/update',
        BANNER_DELETE: '/api/banner/delete',
        BANNER_TOGGLE: '/api/banner/toggle',

        // 文件上传
        UPLOAD_BANNER: '/api/upload/banner',
        UPLOAD_COURSE: '/api/upload/course',
        UPLOAD_ABOUT: '/api/upload/about',

        // 预约相关 可能是假接口
        BOOKING_LIST: '/api/booking/list',
        BOOKING_CREATE: '/api/booking/create',
        BOOKING_CANCEL: '/api/booking/cancel',

        // 新增后端真实接口
        APPOINTMENT: '/api/appointment',
        TIME_SLOT: '/api/time-slot',
        APPOINTMENT_CANCEL: '/api/appointment/cancel',
        APPOINTMENT_CHECK: '/api/appointment/check',
        APPOINTMENT_DELETE: '/api/appointment/delete',

        // 课程相关
        COURSE_LIST: '/api/course/list',
        COURSE_DETAIL: '/api/course/detail',

        // 课程安排相关 (Course Schedule)
        COURSE_SCHEDULE_ADD: '/api/course/add',
        COURSE_SCHEDULE_ALL: '/api/course/all',
        COURSE_SCHEDULE_QUERY: '/api/course/query',
        COURSE_SCHEDULE_QUERY_BY_CLASS: '/api/course/queryByClassId',
        COURSE_SCHEDULE_UPDATE: '/api/course/update',
        COURSE_SCHEDULE_DELETE: '/api/course',

        // 班级相关 (Course Class)
        COURSE_CLASS_LIST: '/api/student-class-hours/classes',

        // 课时相关（保留兼容性）
        HOURS_INFO: '/api/hours/info',
        HOURS_RECHARGE: '/api/hours/recharge',

        // 班级课时相关
        CLASS_HOURS_MY: '/api/student-class-hours/my-hours',

        // 管理员课时管理
        ADMIN_LESSON_ADJUST: '/api/lesson/admin/adjust',
        ADMIN_LESSON_BATCH_RECHARGE: '/api/lesson/admin/batchRecharge',
        ADMIN_LESSON_RECHARGE_LIST: '/api/lesson/admin/getStudentRechargeList',
        ADMIN_LESSON_HANDLE_RECHARGE: '/api/lesson/admin/handleStudentRecharge',
        ADMIN_LESSON_HANDLE_RECHARGE_MULTI: '/api/lesson/admin/handleStudentRechargeMultiClass',
        ADMIN_LESSON_CLASS_PRICES: '/api/lesson/admin/getClassPrices',
        ADMIN_LESSON_PROCESS_LOGS: '/api/lesson/admin/getRechargeProcessLogs',

        // 学生充值申请
        STUDENT_RECHARGE_SUBMIT: '/api/student-class-hours/submitRecharge',


        // 课时管理相关（保留兼容性）
        LESSON_INFO: '/api/lesson/admin/info',
        LESSON_LOGS: '/api/lesson/admin/logs',
        LESSON_ADJUST: '/api/lesson/admin/adjust',

        // 学生课时相关
        STUDENT_LESSON_INFO: '/api/lesson/admin/info',
        STUDENT_LESSON_LOGS: '/api/lesson/admin/logs',


        /*// 🆕 新增：班级课时管理相关
        // 获取学生班级课时信息
        CLASS_HOURS_MY: '/api/student-class-hours/my-hours',
        // 获取所有班级信息
        CLASS_HOURS_CLASSES: '/api/student-class-hours/classes',
        // 获取学生在特定班级的课时
        CLASS_HOURS_STUDENT: '/api/student-class-hours/student',
        // 获取班级的所有学生课时
        CLASS_HOURS_CLASS: '/api/student-class-hours/class',
        // 手动调整课时
        CLASS_HOURS_ADJUST: '/api/student-class-hours/adjust',
        // 获取课时变动日志
        CLASS_HOURS_LOGS: '/api/student-class-hours/logs',
        // 初始化学生班级课时
        CLASS_HOURS_INIT: '/api/student-class-hours/init',*/

        // 管理员课时管理相关
        LESSON_ADMIN_STATS: '/api/lesson/admin/stats',
        LESSON_ADMIN_STUDENTS: '/api/lesson/admin/students',
        LESSON_ADMIN_BATCH_RECHARGE: '/api/lesson/admin/batch-recharge',
        LESSON_ADMIN_BATCH_ADJUST: '/api/lesson/admin/batch-adjust',

        // 充值管理
        LESSON_STUDENT_RECHARGE_LIST: '/api/lesson/admin/getStudentRechargeList',
        LESSON_HANDLE_STUDENT_RECHARGE: '/api/lesson/admin/handleStudentRecharge',
        LESSON_RECHARGE_PROCESS_LOGS: '/api/lesson/admin/getRechargeProcessLogs',

        // 微信支付相关
        PAYMENT_CREATE: '/api/payment/create',
        PAYMENT_NOTIFY: '/api/payment/notify',
        PAYMENT_QUERY: '/api/payment/query',
        PAYMENT_REFUND: '/api/payment/refund',

        // 学生充值相关 (原有)
        STUDENT_SUBMIT_RECHARGE: '/api/student-class-hours/submitRecharge',
        STUDENT_MY_RECHARGE_RECORDS: '/api/student-class-hours/myRechargeRecords',

        // 签到签退相关
        ATTENDANCE_SIGNIN: '/api/attendance/signin',
        ATTENDANCE_SIGNOUT: '/api/attendance/signout',
        ATTENDANCE_TODAY: '/api/attendance/today',
        ATTENDANCE_HISTORY: '/api/attendance/history',
        ATTENDANCE_STATS: '/api/attendance/stats',

        // 签到签退日志相关接口
        ATTENDANCE_LOGS_STUDENT: '/api/attendance/logs/student',
        ATTENDANCE_LOGS_TODAY: '/api/attendance/logs/today',
        ATTENDANCE_LOGS_RECENT: '/api/attendance/logs/recent',

        // 关于我们相关
        ABOUT_US: '/api/aboutUs/getAboutUs',
        ABOUT_US_UPDATE: '/api/aboutUs/update',
        ABOUT_US_UPLOAD: '/upload/image',
        ABOUT_US_DELETE: '/api/aboutUs/delete',

        // 客服联系方式相关
        CUSTOMER_SERVICE: '/api/aboutUs/customer-service',
        CUSTOMER_SERVICE_UPDATE: '/api/aboutUs/customer-service/update'
    }
}

// 获取完整的API URL
export function getApiUrl(endpoint) {
    return `${API_CONFIG.BASE_URL}${endpoint}`
}

// 获取带认证头的请求配置
export function getRequestConfig(token, method = 'GET', data = null) {
    const config = {
        header: {
            'Content-Type': 'application/json'
        }
    }

    if (token) {
        config.header['Authorization'] = `Bearer ${token}`
    }

    if (method) {
        config.method = method
    }

    if (data) {
        config.data = data
    }

    return config
}

// 统一的API请求方法，包含错误处理
export function apiRequest(options) {
    return new Promise((resolve, reject) => {
        console.log('发起API请求:', {
            url: options.url,
            method: options.method,
            data: options.data
        })

        uni.request({
            ...options,
            success: (response) => {
                console.log('API响应:', {
                    statusCode: response.statusCode,
                    data: response.data
                })

                if (response.statusCode === 200) {
                    resolve(response.data)
                } else {
                    // 处理不同的HTTP状态码
                    let errorMessage = '请求失败'

                    if (response.statusCode === 500) {
                        errorMessage = '服务器内部错误，请稍后重试'
                        if (response.data && response.data.message) {
                            errorMessage = response.data.message
                        }
                    } else if (response.statusCode === 400) {
                        errorMessage = '请求参数错误'
                        if (response.data && response.data.message) {
                            errorMessage = response.data.message
                        }
                    } else if (response.statusCode === 404) {
                        errorMessage = '接口不存在'
                    } else if (response.statusCode === 403) {
                        errorMessage = '权限不足'
                    }

                    reject(new Error(`HTTP ${response.statusCode}: ${errorMessage}`))
                }
            },
            fail: (error) => {
                console.error('API请求失败:', error)

                // 处理域名白名单错误
                if (error.errMsg && error.errMsg.includes('url not in domain list')) {
                    uni.showModal({
                        title: '配置提示',
                        content: '请在微信公众平台配置合法域名，或检查API地址是否正确',
                        showCancel: false
                    })
                }

                reject(error)
            }
        })
    })
}

/**
 * 从token中提取wechatId（与后端保持一致）
 * @param {string} token 认证token
 * @return {string} wechatId
 */
export function extractWechatIdFromToken(token) {
    if (token != null && token.startsWith("Bearer ")) {
        token = token.substring(7);
    }

    if (token != null && token.startsWith("token_")) {
        const parts = token.split("_");
        if (parts.length >= 2) {
            return parts[1];
        }
    }

    return null;
}

/**
 * 格式化token为Bearer格式
 * @param {string} token 原始token
 * @return {string} 格式化后的token
 */
export function formatToken(token) {
    if (!token) return '';

    if (token.startsWith('Bearer ')) {
        return token;
    }

    return `Bearer ${token}`;
}

// 检查API连接状态
export function checkApiConnection() {
    return apiRequest({
        url: getApiUrl('/api/health'),
        method: 'GET'
    }).then(() => {
        return true
    }).catch(() => {
        return false
    })
}
